package data.dep;

import java.util.ArrayList;

import data.crawling.Builder;

import websphinx.Crawler;
import websphinx.Element;
import websphinx.Page;
import websphinx.Tag;

/**
 * @deprecated
 * @author j55wu
 *
 */
public 	class ResultTableCrawler extends Crawler{

	public ArrayList<String[]> vendors ;
	
	public ResultTableCrawler(){
		this.vendors = new ArrayList<String[]>();
	}
	
	@Override 
	public void visit(Page page){
		
		//price, name, url, rating
		for(Tag t:page.getTags()){
			boolean found = false;
			if(t.getHTMLAttribute("class") != null
					&& t.getHTMLAttribute("class").compareToIgnoreCase("ps-sellers-table crts")==0){
				//System.out.println(t.getElement());
				for(Element line = t.getElement().getChild(); line!=null; line = line.getSibling()){
					String[] v = new String[4];
					found = false;
					String s=line.getHTMLAttribute("id");
					if(s != null && s.contains("seller")){
						found = true;
						for(Element col = line.getChild(); col!=null; col=col.getSibling()){
							//get vendor name and url
							if(col.getHTMLAttribute("class").contains("seller-col")){
								v[1] = col.getChild().getChild().toText().trim();
								String vurl = col.getChild().getChild().getHTMLAttribute("href").trim();
								vurl = vurl.substring(vurl.indexOf("?q=")+3, vurl.indexOf("&fr="));
								v[2] = vurl;
							}else if(col.getHTMLAttribute("class").contains("rating-col")){
								//get seller rating
								Element span = col.getChild().getChild();
								if(span != null){
									String vrate = span.getHTMLAttribute("title").toString().trim();
									if(vrate.indexOf(' ') >= 0){
										//e.g., 4 stars => 4
										vrate = vrate.substring(0,  vrate.indexOf(' '));
									}
									v[3] = vrate;
								}
							}else if(col.getHTMLAttribute("class").contains("price-col")){
								String price = col.getChild().toText().trim();
								price  = price.substring(price.indexOf('$')+1);//remove the dollar sign
								v[0] = price;
							}
						}

					}else{
						continue;
					}
					if(found){
						for(int i =2 ; i<v.length; i++){
							if(v[i] == null){
								v[i] = Builder.NULL;
							}
						}
						if(v[0]!=null && v[1]!=null){
							this.vendors.add(v);
						}
						
						//System.out.println("rtc vendor added "+this.printVendors(this.vendors));
					}
					
					
				}					
				
			}
			
		}
		
		//end of for loop
	}
	
	
	private String printVendors(ArrayList<String[]> vs){
		String s = "";
		for(String[] v:vs){
			s += "\n"+v[0]+", "+v[1]+", "+v[3];
		}
		return s;
	}
}
